<template>
  <div>
     <el-tag
    v-for="tag in dynamicTags"
    :key="tag.address"
    class="mx-1"
    closable
    :disable-transitions="false"
    @close="handleClose(tag)"
  >
    {{ tag.name }}
  </el-tag>
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="margin-top: 20px"
    >
      <el-row>
        <el-button  @click="dialogTableVisible">
          open a Table nested Dialog
        </el-button>
        <el-col :span="6">
          <el-form-item label="容器" prop="container">
            <el-button
              type="primary"
              size="small"
              @click="workloadVisible = true"
              >选择</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="文件" prop="filename">
            <el-upload
              class="upload-demo"
              action="/api/file/fileupload"
              :limit="3"
              :on-success="handleFileUploadSuccess"
              :on-remove="removeFile"
              :file-list="fileList"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div class="el-upload__tip">文件不能不超过500kb</div>
            </el-upload></el-form-item
          >
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="路径" prop="path">
            <el-input v-model="form.path" placeholder="请输入文件路径" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="success" round @click="submitForm">提交</el-button>
            <el-button type="danger" round @click="clearList"
              >清空列表</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row>
      <el-col :span="21">
        <div class="content">
          <table-enhancer
            :total="state.total"
            v-model:current-page="state.page"
            @current-change="handleCurrentChange"
            showSizes
            @size-change="handleSizeChange"
          >
            <el-table
              :data="selectedContainersShowInList"
              border
              fit
              highlight-current-row
              v-loading="dataLoading"
              element-loading-background="rgba(0, 0, 0, 0.5)"
              element-loading-text="数据正在加载中"
              element-loading-spinner="el-icon-loading"
            >
              <el-table-column prop="cls" label="Cls" />
              <el-table-column prop="namespace" label="NameSpace" />
              <el-table-column prop="name" label="Pod" />
              <el-table-column prop="ip" label="IP" />

              <el-table-column label="操作">
                <template #default="scope">
                  <el-button
                    type="primary"
                    size="mini"
                    plain
                    @click="
                      deleteSelectedContainerFun(
                        scope,
                        selectedContainersShowInList
                      )
                    "
                    >移除</el-button
                  >
                </template>
              </el-table-column>
              <p
                style="text-align: center; line-height: 50px"
                v-loading="loading"
              >
                <a
                  href="javascript:;"
                  v-show="showMore"
                  @click="getMData()"
                  class="blue01"
                  >点击加载更多</a
                >
              </p>
            </el-table>
          </table-enhancer>
        </div>
      </el-col>
    </el-row>
<aa ref="aaRef" @removeItem="removeItem"/>

    <!-- 弹出框 -->
    <containerDialog
      ref="assemblyRef"
      v-model:visible="workloadVisible"
      @handleContainerClick="handleContainerClick"
      @arrangeTableItemSelect="arrangeTableItemSelect"
      @statefulTableItemSelect="statefulTableItemSelect"
      :isClear="isClear"
      :selectedContainers="selectedContainers"
    />
    <!-- <el-dialog title="选择容器" v-model="workloadVisible" width="50%">
      <el-tabs value="first">
        <el-tab-pane label="Workload选择" name="first">
          <el-tree
            ref="treeByWorkload"
            :props="treeProps"
            :load="getTreeByWorkloadFun"
            lazy
            show-checkbox
            highlight-current
          />
        </el-tab-pane>
        <el-tab-pane label="Node选择" name="second">
          <el-tree
            ref="treeByNodename"
            :props="treeProps"
            :load="getTreeByNodeFun"
            lazy
            show-checkbox
            highlight-current
          />
        </el-tab-pane>
        <el-tab-pane label="手动输入IP" name="third">
          <el-select v-model="podipCls" filterable placeholder="请选择集群">
            <el-option
              v-for="item in clusterData"
              :key="item.clsid"
              :label="item.clsName"
              :value="item.clsid"
            />
          </el-select>
          <el-input
            v-model="podipInput"
            type="textarea"
            placeholder="请输入内容"
          />
          <br />
          <el-button
            type="primary"
            size="mini"
            plain
            @click="handleAddListClick"
            >添加至列表</el-button
          >
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="workloadVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleContainerClick"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog> -->
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive, watchEffect, nextTick } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
// import { getList, getClusterList, fileUpload } from "@/api/fileTransfer/script";
import { fileUpload } from "@/api/fileTransfer/script";

import {
  getListSource,
  // getTreeByWorkload,
  // getTreeByNode,
  InsertSelectedContainers,
  getWorkLoadNodes,
  getNodeNodes,
  deleteSelectedContainer,
} from "@/api/fileTransfer/task";
import containerDialog from "../components/containerDialog.vue";
import aa from "../components/aa.vue";

import TableEnhancer from "@/common/components/table-enhancer.vue";

export default defineComponent({
  components: { containerDialog, TableEnhancer,aa },
  setup() {
    const router = useRouter();
    const fileList = ref([]);
    const dataLoading = ref(false);
    const loading = ref(false);
    const pageIndex = ref(1);
    const showMore = ref(false);
    // const selectedContainersShowInList = ref([]);
    const selectedContainersShowInList: any = ref([]);

    const rules = ref({
      container: [
        {
          type: "array",
          required: true,
          message: "请选择容器",
          trigger: "change",
        },
      ],
      path: [{ required: true, message: "请输入文件路径", trigger: "blur" }],
      filename: [{ required: true, message: "请上传文件", trigger: "click" }],
    });
    const state = reactive({
      loading: false,
      page: 1,
      pageSize: 10,
      total: 0,
    });
    const form = reactive<{
      container: number[];
      path: string;
      filename: string;
    }>({
      container: [],
      path: "",
      filename: "",
    });
    // const timeoutOptions = ref([600, 1200, 1800, 2400, 3600]);
    // const scriptData = ref([]);
    // const clusterData = ref([]);
    const selectedContainers = ref([]);
    const treeProps = ref({
      label: "name",
      children: "children",
      isLeaf: "leaf",
    });

    // const getScriptList = async () => {
    //   try {
    //     const { resp } = await getList();
    //     scriptData.value = resp.datalist;
    //   } catch (err: any) {
    //     ElMessage.error(err);
    //   }
    // };
    // getScriptList();

    // const getClusterListFun = async () => {
    //   try {
    //     const { resp } = await getClusterList({ type: "cls" });
    //     clusterData.value = resp.datalist;
    //   } catch (err: any) {
    //     ElMessage.error(err);
    //   }
    // };
    // getClusterListFun();
    const arrangeTableArr = ref([]);
    const statefulTableArr = ref([]);
    const assemblyRef = ref();
    const isClear = ref(false);

    const clearList = () => {
      isClear.value = true;
      selectedContainers.value = [];
      selectedContainersShowInList.value = [];
      arrangeTableArr.value = [];
      statefulTableArr.value = [];
    };
    const slotloading = ref(false);

    const getData = () => {
      slotloading.value = false;
    };

    const getMData = () => {
      pageIndex.value++;

      const listLength = selectedContainersShowInList.value.length;
      selectedContainersShowInList.value = selectedContainers.value.slice(
        0,
        listLength + 5
      );
      loading.value = true;
      getData();
    };

    const fileid = ref("");
    const filename = ref("");
    const fileListUpload = ref();

    const handleFileUploadSuccess = (resp, file) => {
      fileid.value = resp;
      filename.value = file.name;
      fileListUpload.value.push({ fileid: resp, filename: file.name });
      form.filename = file.name;
    };

    const removeFile = () => {
      form.filename = "";
    };

    const InsertSelectedContainers1 = (clsArr, Containers) => {
      Containers = InsertSelectedContainers(clsArr, Containers);
      return Containers;
    };

    const workloadVisible = ref(false);
    // const listSourceData = ref([]);

    const arrangeTableItemSelect = (val) => {
      console.log("部署表格选中", val);
      arrangeTableArr.value = val;
    };
    const statefulTableItemSelect = (val) => {
      console.log("有状态副本集表格选中", val);
      statefulTableArr.value = val;
    };
    const handleContainerClick = async () => {
      dataLoading.value = true;
      workloadVisible.value = false;
      selectedContainersShowInList.value = [
        ...arrangeTableArr.value,
        ...statefulTableArr.value,
      ];
      // const workLoadNodes = arrangeTableArr.value;
      console.log("最后的值", selectedContainersShowInList.value);

      // selectedContainers.value = await getWorkLoadNodes(
      //   workLoadNodes,
      //   selectedContainers.value
      // );

      // const nameNodes = statefulTableArr.value;
      // selectedContainers.value = await getNodeNodes(
      //   nameNodes,
      //   selectedContainers.value
      // );

      dataLoading.value = false;
    };

    // const getTreeByWorkloadFun = (node, resolve) => {
    //   resolve = getTreeByWorkload(
    //     node,
    //     resolve,
    //     // clusterData.value, // 手动输入
    //     listSourceData.value
    //   );
    // };

    // const getTreeByNodeFun = (node, resolve) => {
    //   resolve = getTreeByNode(
    //     node,
    //     resolve,
    //     // clusterData.value,
    //     listSourceData.value
    //   );
    // };

    const formRef = ref();
    const submitForm = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          submit();
        }
      });
    };

    const containerlistselected = ref([]);
    const podipCls = ref("");
    const podipInput = ref("");

    const submit = async () => {
      form.container = selectedContainers.value;
      // let id = 0;
      const resp = await fileUpload({
        containers: selectedContainers.value,
        path: form.path,
        fileid: fileid.value,
        filename: filename.value,
        fileListUpload: [],
      });
      let id = resp.taskid || 0;
      ElMessage.success("success");
      await router.push({ path: "/taskstatus/task/" + id });
    };

    const handleAddListClick = () => {
      getListSource({
        type: "podip",
        clsid: podipCls.value,
        podiplist: podipInput.value,
      }).then((resp) => {
        containerlistselected.value = resp.datalist;
        for (const x in containerlistselected.value) {
          selectedContainers.value = InsertSelectedContainers1(
            containerlistselected.value[x],
            selectedContainers.value
          );
        }
      });
    };

    const deleteSelectedContainerFun = (row, rows) => {
      console.log(1111, row, rows, assemblyRef.value);
      rows = deleteSelectedContainer(row, rows);
      // selectedContainers.value = deleteSelectedContainer(
      //   row,
      //   selectedContainers.value
      // );
      selectedContainers.value = rows;
      selectedContainers.value.forEach((item) => {
        if (item) {
          console.log(9, item);

          nextTick(() => {
            assemblyRef.value.arrangeRef.tableRef.toggleRowSelection(
              item,
              true
            );
          });
        } else {
        }
      });
      if (rows.length == 0) {
        console.log(8);

        assemblyRef.value.arrangeRef.tableRef.clearSelection();
      }
      console.log(2345, selectedContainers.value);
    };
    const handleCurrentChange = (page) => {
      state.page = page;
    };
    const handleSizeChange = (size) => {
      state.pageSize = size;
    };
    // watchEffect(() => {
    //   if (selectedContainers.value.length > 0) {
    //     form.container.push(1);
    //   } else {
    //     form.container = [];
    //   }

    //   if (selectedContainersShowInList.value.length < 10) {
    //     selectedContainersShowInList.value = selectedContainers.value.slice(
    //       0,
    //       10
    //     );
    //   }

    //   if (
    //     selectedContainersShowInList.value.length === 0 ||
    //     selectedContainersShowInList.value.length ===
    //       selectedContainers.value.length
    //   ) {
    //     showMore.value = false;
    //   } else {
    //     showMore.value = true;
    //   }
    // });
    const aaRef = ref()
    const dialogTableVisible =()=>{
aaRef.value.open(dynamicTags.value)
    }
const dynamicTags=ref([])
    const removeItem=(val)=>{
      dynamicTags.value = val
 console.log(333,val, dynamicTags.value);
    }

    const handleClose=(tag)=>{
    const filteredArray = []
   dynamicTags.value.filter(obj => {
      if(obj.date != tag.date)
      filteredArray.push(obj)
      // console.log(111, obj.date,tag.date);
      
      })
       dynamicTags.value = filteredArray
     console.log(444,filteredArray);
     
    }
    return {
      rules,
      dataLoading,
      loading,
      showMore,
      selectedContainersShowInList,
      form,
      treeProps,
      // clusterData,
      workloadVisible,
      podipCls,
      podipInput,
      formRef,
      fileList,
      state,
      assemblyRef,
      isClear,
      selectedContainers,

      clearList,
      getMData,
      handleFileUploadSuccess,
      removeFile,
      handleContainerClick,
      submitForm,
      handleAddListClick,
      deleteSelectedContainerFun,
      // getTreeByNodeFun,
      // getTreeByWorkloadFun,
      arrangeTableItemSelect,
      statefulTableItemSelect,
      handleCurrentChange,
      handleSizeChange,
aaRef,
      dialogTableVisible,
      removeItem,
      dynamicTags,
      handleClose,
    };
  },
});
</script>
